package com.cloudwise.controller;

import com.cloudwise.service.UserInfoService;
import com.cloudwise.service.impl.UserInfoServiceImpl;
import com.cloudwise.util.MyConstants;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;


/**
 * @author ：Teacher陈（86521760@qq.com）
 * @date ：Created in 2021/9/16 11:35
 * @description：用户控制器
 * @modified By：
 * @version: 1.0
 */
@WebServlet(urlPatterns = "/user")
public class UserInfoServlet  extends HttpServlet {
    //获取日志对象
    Logger logger = Logger.getLogger(UserInfoServlet.class);
    UserInfoService userInfoService= new UserInfoServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、设置请求和响应的编码格式
/*        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");*/
        //2、获取所有的参数，封装到map中
        //定义一个map集合封装所有的参数名和值
        Map<String,Object> map = new HashMap();
        //获取所有的参数名集合
        Enumeration<String> parameterNames = req.getParameterNames();
        while (parameterNames.hasMoreElements()){
            String parameterName = parameterNames.nextElement();
            map.put(parameterName, req.getParameter(parameterName));
        }
        /**
         * /user？method=add
         * 	添加 /user？method=add
         * 	删除/user？method=delete
         * 	修改/user？method=update
         * 	查询/user？method=find
         */
        //3、判断method参数的值
        String method=map.get("method")+"";
        switch (method){
            case "add":
                //判断数据库用户名是否存在
                Map<String, Object> userName = userInfoService.findUserByUserName(map.get("username").toString());
                String message;
                if(userName!=null){
                    //用户名存在
                    message=userName.get("username")+"用户名已经存在！";
                    req.setAttribute("message",message);
                    //赶紧回到注册页面，修改用户名
                    req.getRequestDispatcher("register.jsp").forward(req,resp);
                }else
                {
                    //用户名不存在，保存用户信息
                    map.put("createtime",new Date());
                    boolean addUser = userInfoService.addUser(map);
                    if(addUser){
                        //删除之后去查询所有页面
                        this.findAllUser(req,resp,map);
                    }else
                    {
                        resp.sendRedirect("fail.jsp");
                    }
                }
                break;
            case "delete":
                boolean deleteUser = userInfoService.deleteUser(map);
                if(deleteUser){
                    //删除之后去查询所有页面
                    this.findAllUser(req,resp,map);
                }else
                {
                    resp.sendRedirect("fail.jsp");
                }

                break;
            case "update":
                break;
            case "find":
                break;
            default:
                //默认查询所有
                this.findAllUser(req,resp,map);
                break;

        }

    }
    /**
     * @create by: Teacher陈（86521760@qq.com）
     * @description: 通用的查询所有
     * @create time: 2021/9/16 11:49
     * @param req
     * @param resp
     * @return void
     */
    public  void findAllUser(HttpServletRequest req, HttpServletResponse resp, Map map) throws ServletException, IOException {
      /*  logger.trace("查询操作trace");
        logger.debug("查询操作debug");
        logger.info("查询操作info");
        logger.warn("查询操作warn");
        logger.error("查询操作error");
        logger.fatal("查询操作fatal");*/
        //需要分页参数
        Object pageNoObj= map.get("pageNo");
        int  pageNo=0;
        if (pageNoObj == null||Integer.parseInt(pageNoObj.toString())<1) {
            pageNo = MyConstants.PAGE_NO;
           map.put("pageNo",pageNo);
        }
        int pageSize=0;
        if (map.get("pageSize") == null) {
            pageSize = MyConstants.PAGE_SIZE;
           map.put("pageSize",pageSize);
        }
        List<Map<String, Object>> allUserInfo = userInfoService.findAllUserInfo(map);
        HttpSession session = req.getSession();

        //获取总条数和总页数
        int rowCount = userInfoService.findAllCount();
        int pageNoCount=0;
        //计算总页数
        pageSize=Integer.parseInt(map.get("pageSize").toString());
        if(rowCount%pageSize==0){
            pageNoCount=rowCount/pageSize;
        }else
        {
            pageNoCount=rowCount/pageSize+1;
        }
        session.setAttribute("pageNo",map.get("pageNo"));
        session.setAttribute("pageSize",map.get("pageSize"));
        session.setAttribute("pageNoCount",pageNoCount);
        session.setAttribute("rowCount",rowCount);
        session.setAttribute("allUserInfo",allUserInfo);
        req.getRequestDispatcher("showUser.jsp").forward(req,resp);
    }
}
